from django.shortcuts import render, redirect
from cla import models


# Create your views here.
def cla(request):
    cla_list = models.Cla.objects.all().order_by('cid')
    return render(request, 'cla.html', {'cla_list': cla_list})


def add_cla(request):
    error = ''
    if request.method == 'POST':
        cla = request.POST['cla'].strip()
        obj = models.Cla.objects.filter(name=cla)
        if obj:
            error = '已存在'
        elif not cla:
            error = '不能为空'
        else:
            models.Cla.objects.create(name=cla)
            return redirect('/cla/')
    return render(request, 'add_cla.html', {'error': error})


def del_cla(request):
    pk = request.GET.get('id')
    obj = models.Cla.objects.get(pk=pk)
    obj.delete()
    return redirect('/cla/')


def alter_cla(request):
    error = ''
    pk = request.GET.get('id')
    obj = models.Cla.objects.get(pk=pk)
    if request.method == 'POST':
        cla = request.POST['cla'].strip()
        cla_list = models.Cla.objects.filter(name=cla)
        if obj.name == cla:
            error = '无修改'
        elif cla_list:
            error = '已存在'
        else:
            obj.name = cla
            obj.save()
            return redirect('/cla/')
    return render(request, 'alter_cla.html', {'error': error, 'obj': obj})


def student(request):
    student_list = models.Student.objects.all().order_by('sid')
    return render(request, 'student.html', {'student_list': student_list})


def add_student(request):
    error = ''
    cla_list = models.Cla.objects.all().order_by('cid')
    if request.method == 'POST':
        student = request.POST['student']
        cla_id = request.POST['cla_id']
        obj = models.Student.objects.filter(name=student)
        if obj:
            error = '学生已存在;'
        else:
            models.Student.objects.create(name=student, cla_id=cla_id)
            error = '添加成功'
    return render(request, 'add_student.html', {'cla_list': cla_list, 'error': error})


def alter_student(request):
    error = ''
    student = models.Student.objects.get(pk=request.GET.get('id'))
    cla_list = models.Cla.objects.all()
    if request.method == 'POST':
        student_name = request.POST['student'].strip()
        cid = int(request.POST['cid'])
        if cid == student.cla_id and student_name == student.name:
            error = '无修改'
            return render(request, 'alter_student.html', {'cla_list': cla_list, 'student': student, 'error': error})
        student.name = student_name
        student.cla_id = cid
        student.save()
        return redirect('/student/')
    return render(request, 'alter_student.html', {'cla_list': cla_list, 'student': student, 'error': error})


def del_student(request):
    pk = request.GET.get('id')
    obj = models.Student.objects.get(pk=pk)
    obj.delete()
    return redirect('/student/')
